package com.chwn.curiousdiary.ui.register;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.ui.main.MainActivity;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.RegisterBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.utils.CustomToast;
import com.chwn.curiousdiary.utils.DialogUtil;
import com.chwn.curiousdiary.utils.SendCodeUtil;
import com.chwn.harulib.base.BaseActivity;
import com.chwn.harulib.mvp.rx.HttpResult;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by Myshikin on 2017/6/17.
 */

public class VerifyCodeActivity extends BaseActivity {

    @BindView(R.id.et_verify_code)
    EditText mVerifyCode;
    @BindView(R.id.tv_resend)
    TextView mCodeTV;

    private String phone;
    private int    mPageType;

    private String unionid;

    private RegisterBean registerInfo;
    private User         user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        super.onCreate(savedInstanceState);


        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_verify_code;
    }

    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.ClOSE_SELF:
                finish();
                if (EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().unregister(this);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        super.initData();
        phone = getIntent().getStringExtra(Constant.PHONE);
        mPageType = getIntent().getIntExtra(Constant.JUMP_TYPE, Constant.BIND_PHONE);
        unionid = getIntent().getStringExtra(Constant.UNION_ID);
        registerInfo = (RegisterBean) getIntent().getSerializableExtra(Constant.IS_REGISTER);
        user = (User) getIntent().getSerializableExtra(Constant.USER);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        setBackTVisible(true);
        setBackIcon(R.drawable.icon_back_light);
        Timer timer = new Timer();
        timer.schedule(new Task(0), 0L, 1000L);
    }

    @OnClick({R.id.tv_resend, R.id.ll_back, R.id.iv_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_resend:
                if (!isSend) {
                    sendVerifyCode();
                }
                break;
            case R.id.iv_next_step:
                String s = mVerifyCode.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    CustomToast.showShortToast("请输入验证码");
                } else if (!registerInfo.getNumber().equals(s)) {
                    CustomToast.showShortToast("验证码错误");
                } else {
                    if (registerInfo != null && "1".equals(registerInfo.getIsRegister()) && mPageType == Constant.BIND_PHONE) {  // 绑定已注册手机
                        bindRegistePhone();
                    } else {
                        Intent intent = new Intent(VerifyCodeActivity.this, PassWordActivity.class);
                        intent.putExtra(Constant.JUMP_TYPE, mPageType);
                        intent.putExtra(Constant.UNION_ID, unionid);
                        intent.putExtra(Constant.PHONE, phone);
                        intent.putExtra(Constant.USER, user);
                        intent.putExtra(Constant.VERIFY_CODE, Integer.parseInt(registerInfo.getNumber()));
                        startActivity(intent);
                    }
                }
                break;
        }
    }

    /**
     * 微信绑定已注册手机号
     */
    private void bindRegistePhone() {
        NetWork.getInstance()
                .getApiService(IUserApi.class)
                .userBindPhone(phone, null, unionid, Constant.OSTYPE, Integer.parseInt(mVerifyCode.getText().toString().trim()))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showWaitDialog("请稍等...");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }

    private Observer<HttpResult<List<User>>> mObserver = new Observer<HttpResult<List<User>>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            DialogUtil.dismissWaitDialog();
            errAction("");
        }

        @Override
        public void onNext(HttpResult<List<User>> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }

            List<User> resdata = result.getResdata();
            User user = resdata.get(0);

            user.setIconNum(VerifyCodeActivity.this.user.getIconNum());
            user.setKeepDay(VerifyCodeActivity.this.user.getKeepDay());
//            user.setUserToken(VerifyCodeActivity.this.user.getUserToken());
            DiaryApplication.mInstance.saveUser(user);
            if (!TextUtils.isEmpty(user.getBabybirth())) {
                startActivity(new Intent(VerifyCodeActivity.this, MainActivity.class));
            } else {
                Intent intent = new Intent(VerifyCodeActivity.this, BabySexActivity.class);
                intent.putExtra(Constant.PHONE, phone);
                intent.putExtra(Constant.UNION_ID, unionid);
                startActivity(intent);
            }
        }
    };

    private boolean isSend = true;

    private void sendVerifyCode() {
        SendCodeUtil.sendVerifyCode(phone, mPageType, unionid, new SendCodeUtil.CallBack() {
            @Override
            public void onStart() {
                CustomToast.showShortToast("验证码已发送");
                isSend = true;
            }

            @Override
            public void onSuccess(RegisterBean info) {
                VerifyCodeActivity.this.registerInfo = info;
                Timer timer = new Timer();
                timer.schedule(new Task(0), 0L, 1000L);
            }

            @Override
            public void onFail(String text, int backType) {
                CustomToast.showShortToast(text);
                isSend = true;
            }
        });
    }


    /**
     * 验证码重新发送时间设置
     */
    private class Task extends TimerTask {
        private int time = 90;
        private int tag;

        public Task(int tag) {
            this.tag = tag;
        }

        @Override
        public void run() {
            Message message = handler.obtainMessage();
            message.what = tag;
            message.arg1 = time;
            handler.sendMessage(message);
            time--;
            if (time < 0) {
                cancel();
                isSend = false;
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (mCodeTV == null)
                        return;
                    mCodeTV.setText(msg.arg1 + "秒");
                    if (msg.arg1 == 0) {
                        int color = getResources().getColor(R.color.send_verify_code);
                        mCodeTV.setText("重新发送");
                        mCodeTV.setEnabled(true);
                        mCodeTV.setTextColor(color);
                    }
                    break;
            }

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    private void errAction(String errorMsg) {
        String text;
        if (TextUtils.isEmpty(errorMsg)) {
            text = "请检查网络链接";
        } else {
            text = errorMsg;
        }

        CustomToast.showShortToast(text);
    }

    void showWaitDialog(String text) {
        DialogUtil.showWaitDialog(VerifyCodeActivity.this, text, false);
    }
}
